#-*-coding: utf-8 -*-

import time
import serial

import myconvert

def SearchPort(num=20):
    port_list = []
    for idx in range(num):
        name = 'COM' + str(idx)
        try:
            ser = serial.Serial(name)
            ser.open
            if ser.is_open:
                port_list.append(name)
                ser.close
        except serial.serialutil.SerialException:
            pass
    return port_list

def OpenPort(port, baud_rate=9600, parity=serial.PARITY_NONE):
    try:
        ser = serial.Serial(port, baud_rate, parity=parity) # 8-data bits/1-stop bits
        print("%s is opened, baudrate is %d." %(port, baud_rate), end="\n")
        return ser
    except:
        return None

def ClosePort(ser):
    try:
        if ser.is_open:
            print("%s is closed." %(ser.name), end="\n")
            ser.close()
    except:
        pass

def ReadData(ser):
    try:
        if ser.is_open:
            raw_data = ser.read(ser.in_waiting)
            if len(raw_data) != 0:
                return (True, len(raw_data), myconvert.ToIntList(raw_data))
            else:
                return (True, 0, None)
    except:
        return (False, 0, None)

def WriteData(ser, data):
    try:
        if ser.is_open:
            if type(data) != type(b'\x00'):
                data = myconvert.ToBytes(data)
            ser.write(data)
            time.sleep(1 / ser.baudrate * len(data) * 10)
    except:
        return None
